"use client"

import { useState } from 'react'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { useToast } from '@/components/ui/use-toast'
import { LogIn, Key, AlertCircle, User, Lock, EyeOff, Eye } from 'lucide-react'
import { useRouter } from 'next/navigation'

interface LoginProps {
  onLoginSuccess: () => void
}

export default function Login({ onLoginSuccess }: LoginProps) {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [rememberMe, setRememberMe] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const { toast } = useToast()
  const router = useRouter()

  // 处理登录
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 表单验证
    if (!username || !password) {
      setError('请输入用户名和密码')
      return
    }
    
    setIsLoading(true)
    setError(null)
    
    try {
      // 调用后端API进行验证
      const response = await fetch('/api/admin/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });
      
      if (response.ok) {
        const data = await response.json();
        
        // 登录成功，保存令牌
        if (rememberMe) {
          // 将登录信息存储在localStorage中
          localStorage.setItem('admin_auth', JSON.stringify({
            token: data.token,
            username: data.username,
            userId: data.userId,
            permissions: data.permissions
          }))
        } else {
          // 将登录信息存储在sessionStorage中
          sessionStorage.setItem('admin_auth', JSON.stringify({
            token: data.token,
            username: data.username,
            userId: data.userId,
            permissions: data.permissions
          }))
        }
        
        toast({
          title: '登录成功',
          description: '欢迎回来，' + data.username + '！',
        })
        
        // 通知父组件登录成功
        onLoginSuccess()
      } else {
        // 登录失败
        const errorData = await response.json();
        setError(errorData.message || '用户名或密码错误');
        toast({
          variant: 'destructive',
          title: '登录失败',
          description: errorData.message || '请检查您的用户名和密码',
        })
      }
    } catch (err) {
      console.error('登录错误:', err)
      setError('登录时发生错误，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }
  
  return (
    <div className="flex items-center justify-center min-h-screen bg-[#0c0f14] p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center">
              <Key className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-2xl font-bold text-white mb-1">管理员登录</h1>
          <p className="text-gray-400">请登录以继续访问Tooth Meter</p>
        </div>
        
        <Card className="border border-gray-800 bg-[#1a1d24]">
          <CardHeader>
            <CardTitle>管理员账户</CardTitle>
            <CardDescription>使用您的管理员凭据访问</CardDescription>
          </CardHeader>
          <CardContent>
            {error && (
              <div className="p-3 mb-4 rounded-md bg-red-950 border border-red-800 text-red-300 flex items-start">
                <AlertCircle className="h-5 w-5 mr-2 mt-0.5 flex-shrink-0" />
                <p className="text-sm">{error}</p>
              </div>
            )}
            
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="username">用户名</Label>
                <div className="relative">
                  <User className="absolute left-3 top-3 h-4 w-4 text-gray-500" />
                  <Input
                    id="username"
                    placeholder="输入您的用户名"
                    className="pl-10 bg-[#252a33] border-gray-700"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    disabled={isLoading}
                  />
                </div>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="password">密码</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-500" />
                  <Input
                    id="password"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="输入您的密码"
                    className="pl-10 pr-10 bg-[#252a33] border-gray-700"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={isLoading}
                  />
                  <button
                    type="button"
                    className="absolute right-3 top-3 text-gray-500 hover:text-gray-300"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Checkbox 
                    id="remember"
                    checked={rememberMe}
                    onCheckedChange={(checked) => setRememberMe(checked === true)}
                  />
                  <Label htmlFor="remember" className="text-sm cursor-pointer">记住我</Label>
                </div>
                
                <button
                  type="button"
                  className="text-sm text-blue-500 hover:text-blue-400 hover:underline"
                >
                  忘记密码?
                </button>
              </div>
              
              <Button 
                type="submit" 
                className="w-full bg-blue-600 hover:bg-blue-700 flex items-center justify-center gap-2"
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    正在登录...
                  </>
                ) : (
                  <>
                    <LogIn className="h-4 w-4" />
                    登录
                  </>
                )}
              </Button>
            </form>
          </CardContent>
          <CardFooter className="flex flex-col space-y-4 border-t border-gray-800 pt-4">
            <p className="text-xs text-gray-500 text-center">
              登录即表示您同意遵守我们的管理员条款和隐私政策
            </p>
            
            <div className="text-xs text-gray-500 text-center">
              <p>仅限授权人员访问。未经授权使用本系统将被追究法律责任。</p>
            </div>
          </CardFooter>
        </Card>
        
        <div className="mt-4 text-center text-sm text-gray-500">
          <p>Copyright ©2025 CNTIER - Tooth Meter</p>
          <p>R8ns All rights reserved.</p>
        </div>
      </div>
    </div>
  )
} 